import os
import shutil
import time
import uuid

from django.shortcuts import render
from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated

from doctor.models import Doctor
from orders.models import Order1, Order2, Order3
from orders.serial import Order1Serializer, Order2Serializer, Order3Serializer
from dingxiang_doctor.utils.comm import get_alipay
from dingxiang_doctor.utils.myredis import r

# Create your views here.
class OrderAPIView(APIView):
    permission_classes = [IsAuthenticated]

    # 查询用户订单
    def get(self, request):
        user = request.user
        status = request.query_params.get("status")
        if hash(user.id) % 3 == 0:
            orders = Order1.objects.filter(user=user, status=status)
            ser = Order1Serializer(orders, many=True)
        elif hash(user.id) % 3 == 1:
            orders = Order2.objects.filter(user=user, status=status)
            ser = Order2Serializer(orders, many=True)
        else:
            orders = Order3.objects.filter(user=user, status=status)
            ser = Order3Serializer(orders, many=True)
        return Response({"status": 200, "message": "订单获取成功", "data": ser.data})

    # 新增用户订单
    def post(self, request):
        user = request.user
        doctor_id = request.data.get("doctor")
        doctor = Doctor.objects.get(id=doctor_id)
        price = doctor.price
        detail = request.data.get("detail")
        if hash(user.id) % 3 == 0:
            ser = Order1Serializer(data={"id": 0, "user": user.id, "doctor": doctor.id, "price": price, "detail": detail})
        elif hash(user.id) % 3 == 1:
            ser = Order2Serializer(data={"id": 0, "user": user.id, "doctor": doctor.id, "price": price, "detail": detail})
        else:
            ser = Order3Serializer(data={"id": 0, "user": user.id, "doctor": doctor.id, "price": price, "detail": detail})
        if ser.is_valid():
            ser.save()
            return Response({"status": 200, "message": "订单创建成功", "data": ser.data})
        else:
            return Response({"status": 400, "message": "订单创建失败", "data": ser.errors})

# 大文件上传(上传病历)
class FileUploadView(APIView):
    permission_classes = [IsAuthenticated]
    def post(self, request):
        user_id = request.user.snow_id
        file = request.FILES.get("file")
        filename = request.data.get("filename")
        count = request.data.get("count")
        tcount = request.data.get("tcount")
        totalSize = request.data.get("totalSize")

        # 系统自动生成文件id
        fname = uuid.uuid1().hex

        # 存入redis中，准备celery判断文件是否传输失败
        r.zset_zadd("file_time", time.time(), f"{user_id}{filename}")
        r.zset_zadd("file_size", totalSize, f"{user_id}{filename}")

        # 获取后缀
        arr = filename.split(".")
        filepath = f'static/upload/{user_id}{filename}'
        print("filepath:", os.getcwd())
        if not os.path.exists(filepath):
            os.mkdir(filepath)

        with open(f'static/upload/{user_id}{filename}/{count}', 'wb') as f:
            for chunk in file.chunks():
                f.write(chunk)

        total_size = 0
        for dirpath, dirnames, filenames in os.walk(filepath):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                if os.path.exists(fp):
                    total_size += os.path.getsize(fp)
        fsize = os.path.getsize(filepath)
        print("totalSize:", totalSize)
        print("total_size:", total_size)
        print("fsize:", fsize)
        if int(totalSize) == total_size:
            print("开始合并")
            # 合并
            with open(f'static/upload/{fname}.{arr[-1]}', 'wb') as f:
                for i in range(int(tcount)):
                    with open(f'static/upload/{user_id}{filename}/{i}', 'rb') as f1:
                        f.write(f1.read())
            # 删除临时文件夹
            if os.path.exists(filepath):
                shutil.rmtree(filepath)

            # 删除redis中记录
            r.zset_zrem("file_time", f"{user_id}{filename}")
            r.zset_zrem("file_size", f"{user_id}{filename}")

            return Response({"msg": "ok", "code": 200})
        else:
            return Response({"msg": "ok", "code": 10011})


# 支付订单
class IndexView(APIView):
    def get(self, request):
        alipay = get_alipay()
        link = alipay.direct_pay(out_trade_no='2024101600092836481', total_amount=0.01, subject='买了个火箭')
        pay_url = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?{0}".format(link)
        print('查看支付宝返回结果')
        print(pay_url)
        print('支付宝返回结束')
        return Response({"message": "支付链接已经生成", "url": pay_url})
